<?php
namespace plugins\order\controller;
use cmf\controller\ApiPluginBaseController;
use think\Db;
use plugins\order\model\OrderNumTmpModel;
// use plugins\goods\controller\ApiFreightPluginController;
use plugins\member\model\MemberShipAddressModel;
use plugins\order\model\OrderMemberModel;
use plugins\order\model\OrderModel;
use plugins\goods\model\GoodsSpecListModel;
use plugins\goods\model\GoodsSpecAttrModel;
use plugins\order\model\OrderConsigneeModel;
use plugins\order\model\OrderGoodsListModel;
use plugins\order\model\OrderLogModel;
use plugins\fund\model\FundModel;
//此处保存订单创建相关方法接口
class ApiCreateOrderController extends ApiPluginBaseController
{
	//创建一个用户订单的编号返回前端
	public function createMemberOrderNum()
	{
		//删除过期订单号
		( new OrderNumTmpModel )->where(['time'=>['<',time()]])->delete();
		//生成唯一的编号
		$order_member_num = uniqid('order_member_');
		//30分钟过期
		$result = ( new OrderNumTmpModel )->save(['order_num'=>$order_member_num,'time'=>time()+30*60]);
		if($result){
			return api_json_echo(true,'用户订单编号创建完成',$order_member_num);
		}
		return api_json_echo(true,'用户订单编号创建失败请重试');

	}
	//订单结算界面
	public function OrderSubmit()
	{
		$post = $this->request->post();
		$user = $this->getIdentity();
		checkParam(['sku'=>['name'=>'商品sku'],'num'=>['name'=>'商品数量']],$post);
		$arr = [];
		$sku_list = explode(',', $post['sku']);
		$num_list = explode(',', $post['num']);
		$list = [];
		foreach ($sku_list as $key => $value) {
			$list[$key]['sku'] = $value;
			$list[$key]['num'] = $num_list[$key];
		}
		foreach ($list as $key => $value) {
			$set = [];
			//sku搜索商品规格
			$info = ( new GoodsSpecListModel )->where(['sku'=>$value['sku']])->find();
			if($info == null){
				continue;
			}
			//商品id
			$gid = $info['gid'];
			$goods = db('goods')->where(['id'=>$gid])->find();
			// 商品名
			$set['goods_name'] = $goods['goods_name'];
			if($info['num'] < $value['num']){
				return api_json_echo(false,$set['goods_name'].'库存不足！');
			}
			//商品图片
			if(!empty($info['img'])){
				$set['goods_img'] = zy_domain().$info['img'];
			}else{
				$set['goods_img'] = zy_domain().$goods['goods_img'];
			}

			//商品数量
			$set['num'] = $value['num'];
			//商品sku
			$set['sku'] = $value['sku'];
			//商品价格
			$set['price'] = $info['price'];
			//商品规格
			$attr = '';
			foreach (explode('#*_*#', $info['attr']) as $key => $value) {
				$attr_model = ( new GoodsSpecAttrModel )->get(['attr_id'=>$value]);
				if($attr_model != null){
					$attr .= $attr_model->attr_name.",";
				}

			}
			$attr = rtrim($attr,',');
			$set['attr'] = $attr;
			$arr[$goods['store_id']]['info'][] = $set;
			$store = db('store')->where(['store_id'=>$goods['store_id']])->find();
			if($store != null){
				$arr[$goods['store_id']]['store_name'] = $store['store_name'];
				$arr[$goods['store_id']]['store_id'] = $store['store_id'];
			}
		}
		$tmp = [];
		foreach ($arr as $key => $value) {
			$tmp[] = $value;
		}
		return api_json_echo(true,'查询完成',$tmp);
	}
	//创建用户订单
	public function createMemberOrder()
	{
		$post = $this->request->post();
		$user = $this->getIdentity();
		//传参检测
		$checkParam = [];
		$checkParam['order_member_num'] = ['name'=>'订单编号'];
		$checkParam['order_store_id'] = ['name'=>'店铺id'];
		$checkParam['order_goods_num'] = ['name'=>'商品数量'];
		$checkParam['order_goods_sku'] = ['name'=>'商品sku'];
		$checkParam['consignee_id'] = ['name'=>'默认收货地址'];
		checkParam($checkParam,$post);
		//大订单编号
		$order_member_num = $post['order_member_num'];
		$money = 0;
		$order_list = [];
		//删除过期订单号
		( new OrderNumTmpModel )->where(['time'=>['<',time()]])->delete();
		//判断是否有订单号记录
		$check = ( new OrderNumTmpModel )->get(['order_num'=>$order_member_num]);
		if($check){
			//除去已使用的订单号
			( new OrderNumTmpModel )->where(['order_num'=>$order_member_num])->delete();
		    //开启事务操作
		    Db::startTrans();
		    try{
				$store_list = explode(',', $post['order_store_id']);
				$sku_list = explode(',', $post['order_goods_sku']);
				$num_list = explode(',', $post['order_goods_num']);
				$goods = [];
				foreach ($store_list as $key => $value) {
					$goods[$value][] = ['order_goods_num'=>$num_list[$key],'order_goods_sku'=>$sku_list[$key]];
				}
				//备注的列表
				$remark = htmlspecialchars_decode($post['remark']);
				$remark = $this->string2array($remark);
				foreach ($goods as $key => $value) {
					$arr = [];
					$arr['order'] = $post['order'];
					$arr['order']['store_id'] = $key;
					$arr['goods'] = $value;
					//备注
					$arr['remark'] = array_shift($remark);
					//收货地址id
					$consignee_id = $post['consignee_id'];
					//得到存储的用户收货地址模型
					$consignee = (new MemberShipAddressModel)->get(['id'=>$consignee_id,'uid'=>$user->uid]);
					//排序后 省市区
					$address = (array)(json_decode($consignee->show_address));
					ksort($address);
					//收货人姓名
					$arr['consignee']['order_consignee_name'] = $consignee->receive_name;
					//省
					$arr['consignee']['order_consignee_provice'] = reset($address);
					//详细地址
					$arr['consignee']['order_address'] = '';
					foreach ($address as $k => $address_v) {
						$arr['consignee']['order_address'] .= $address_v;
					}
					$arr['consignee']['order_address_detail'] = $consignee->address;
					$address = json_encode($address);
					$arr['consignee']['order_consignee_address'] = $address;
					//邮编
					$arr['consignee']['order_consignee_postal'] = $consignee->postal_code;
					//收货人手机号
					$arr['consignee']['order_consignee_phone'] = $consignee->receive_phone;
					//创建店铺订单,返回单个订单的金额
					$OrderModel = new OrderModel();
					$return = $OrderModel->createOrder($arr,$arr['consignee']['order_consignee_provice'],$user);
					$money += $return['money'];
					$order_list[] = $return['order_num'];
				}
				//主表存储
				$data = [];
				// $data['member_id'] = $post['order']['member_id'];
				$data['member_id'] = $user->uid;
				$data['order_member_num'] = $post['order_member_num'];
				$data['order_num'] = json_encode($order_list);
				$data['money'] = $money;
				$data['time'] = time();
				$return = ( new OrderMemberModel )->save($data);
				if($return){
					//生成支付记录
					//创建流水号
					// $FundModel = new FundModel();
					// $fund['uid'] = $user->uid;
					// $fund['money'] = $money;
					// $fund['other'] = $order_member_num;
					// $fund_return = $FundModel->addRecord($fund);
					// if($fund_return['status'] == 'success'){
				        // 提交事务
		        		Db::commit();
						return api_json_echo(true,'创建完成',['order_member_num'=>$order_member_num,'time'=>time()]);
					// }else{
					// 	return api_json_echo(false,'创建失败，流水号创建失败，请重试');
					// }
				}
		    }catch(\Exception $e){
		        // 回滚事务
		        Db::rollback();
		    }
			return api_json_echo(false,'创建失败');
		}
		return api_json_echo(false,'错误引用，请刷新页面，没有该订单编号');
	}
	function string2array($data) {
		$data = trim($data);
		if($data == '') return array();
		if(strpos($data, 'array')===0){
			@eval("\$array = $data;");
		}else{
			if(strpos($data, '{\\')===0) $data = stripslashes($data);
			$array=json_decode($data,true);
			// if(strtolower(CHARSET)=='gbk'){
			// 	$array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
			// }
		}
		return $array;
	}
}